package cn.itsource.ymcc.web.controller;

import cn.itsource.result.JSONResult;
import cn.itsource.result.PageList;
import cn.itsource.ymcc.doc.CourseDoc;
import cn.itsource.ymcc.query.CourseDocQuery;
import cn.itsource.ymcc.repository.CourseRepository;
import com.alibaba.fastjson.JSON;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/search")
public class SearchController {
    @Autowired
    private CourseRepository courseRepository;


    @PostMapping("/getCourseInfo")
    public JSONResult getCourseInfo(@RequestBody List<Long> courseIds){
        Iterable<CourseDoc> courseInfos = courseRepository.findAllById(courseIds);
        return JSONResult.success(courseInfos);
    }



    /**
     * 批量添加课程文档数据， - 课程服务通过openfeign来调用  课程上线
     * @param courseDocList
     * @return
     */
    @PostMapping("/saveBatch")
    public JSONResult saveBatch(@RequestBody List<CourseDoc> courseDocList){
        courseRepository.saveAll(courseDocList);
        return JSONResult.success();
    }

    /**
     * 通过id集合批量删除课程文档数据，-  课程服务通过openfeign来调用 课程下线
     * @param courseIds
     * @return
     */
    @DeleteMapping("/deleteBatch")
    public JSONResult deleteBatch(@RequestBody List<Long> courseIds) {
        for (Long courseId : courseIds) {
            courseRepository.deleteById(courseId);
        }
        return JSONResult.success();
    }

    /**
     * 课程搜索
     * @param query
     * @return
     */
    @PostMapping("/search")
    public JSONResult search(@RequestBody CourseDocQuery query){
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        BoolQueryBuilder bool = QueryBuilders.boolQuery();
        //分词匹配查询 match
        if(StringUtils.hasText(query.getKeyword())){
            bool.filter().add(QueryBuilders.matchQuery("name",query.getKeyword()));
        }

        //不分词 term
        if(query.getCourseTypeId() !=null){
            bool.filter().add(QueryBuilders.termQuery("courseTypeId",query.getCourseTypeId()));
        }

        if(StringUtils.hasText(query.getCourseTypeName())){
            bool.filter().add(QueryBuilders.termQuery("courseTypeName",query.getCourseTypeName()));
        }

        if(query.getGradeId() !=null){
            bool.filter().add(QueryBuilders.termQuery("gradeId",query.getGradeId()));
        }

        if(StringUtils.hasText(query.getGradeName())){
            bool.filter().add(QueryBuilders.termQuery("gradeName",query.getGradeName()));
        }

        if(query.getPriceMin() !=null){
            bool.filter().add(QueryBuilders.rangeQuery("price").gte(query.getPriceMin()));
        }

        if(query.getPriceMax() !=null){
            bool.filter().add(QueryBuilders.rangeQuery("price").lte(query.getPriceMax()));
        }

        queryBuilder.withQuery(bool);

        //分页
        Pageable pageable = PageRequest.of(query.getPage() - 1, query.getRows());
        queryBuilder.withPageable(pageable);

        //排序
        SortOrder sortOrder = SortOrder.DESC;//默认降序
        if("asc".equalsIgnoreCase(query.getSortType())){
            sortOrder = SortOrder.ASC;//如果传入的是升序就修改排序规则
        }
        SortBuilder sortBuilder = SortBuilders.fieldSort(query.getSortField()).order(sortOrder);
        queryBuilder.withSort(sortBuilder);

        //执行搜索
        Page<CourseDoc> page = courseRepository.search(queryBuilder.build());
        System.out.println("当前页码："+page.getNumber());
        System.out.println("每页条数："+page.getSize());
        System.out.println("总页数："+page.getTotalPages());
        System.out.println("总条数："+page.getTotalElements());
        System.out.println("当前页条数："+page.getNumberOfElements());
        //当前页的数据的集合
        List<CourseDoc> content = page.getContent();
        PageList<CourseDoc> pageList = new PageList<>(page.getTotalElements(), content);

        return JSONResult.success(pageList);
    }

}
